import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }


    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService executorService = Executors.newWorkStealingPool();
        while(true){
            // 通过accept方法，把内核中已经建立好的连接拿到应用程序中。
            // 建立连接的细节流程是由内核自动完成的。
            Socket clientSocket = serverSocket.accept();
           // processConnection(clientSocket);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

    }
    // 通过这个方法，来处理连接
    public void processConnection(Socket clinetSocket) throws IOException {
        // 进入方法，先打印一个日志，表示当前有客户端连接上了。
        System.out.printf("[%s:%d] 客户端上线！\n",clinetSocket.getInetAddress(),clinetSocket.getPort());
        // 进行数据交互
        try(InputStream inputStream = clinetSocket.getInputStream();
            OutputStream outputStream = clinetSocket.getOutputStream()){
            //使用太容易（）方式，避免使用完流对象之后忘记关闭
            //由于客户端发来的数据可能是多条，使用循环合适

            while(true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    //连接断开
                    System.out.printf("[%s:%d] 客户端下线!\n",clinetSocket.getInetAddress(),clinetSocket.getPort());
                    break;
                }
                // 1.读取请求并解析 scanner.next规则是：读到”空白符“返回.
                String request = scanner.next();
                // 2.根据请求计算响应
                String response = process(request);
                // 3. 把响应写回到客户端
                PrintWriter  printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                // 此处的println将响应写入到output Stream对应的流对象中即client Socket
                printWriter.flush();
                // 4. 打印请求交互的内容
                System.out.printf("[%s:%d] req=%s , resp = %s\n",clinetSocket.getInetAddress(),clinetSocket.getPort(),
                request,response);



            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            clinetSocket.close();

        }

    }
    public String process(String request){
        return  request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
